package cn.seaboot.admin.rabbit.test;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeoutException;

/**
 * @author Mr.css
 * @version 2020-11-12 19:30
 */
public class ExchangePublish {
    /**
     * 队列名称
     */
    private static final String QUEUE_NAME = "queue_name";
    /**
     * 路由键，交换机会根据路由键，把消息推到队列，
     * 如果路由键与队列名称一致的情况，消息会被精准推送到同名的队列
     */
    private static final String ROUTING_KEY = "queue_name";
    /**
     * 交换机名称
     */
    private static final String EXCHANGE = "exchanges";

    public static void main(String[] args) {
        try {
            Connection connection = ConnectionUtil.getConnection();
            Channel channel = connection.createChannel();

            // 声明队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            // 声明交换机
            channel.exchangeDeclare(EXCHANGE, BuiltinExchangeType.DIRECT);
            // 声明一个绑定：队列绑定到交换机
            channel.queueBind(QUEUE_NAME,EXCHANGE,ROUTING_KEY);
            // 声明一个绑定：交换机绑定到交换机
            // channel.exchangeBind(EXCHANGE,EXCHANGE,ROUTING_KEY);

            int cnt = 10;
            while (cnt-- > 0) {
                String message = "This is simple queue:" + cnt;

                // 通过交换机，把消息发送到推送到队列中
                channel.basicPublish(EXCHANGE, ROUTING_KEY, null, message.getBytes(Charset.defaultCharset()));
                System.out.println("[send]：" + message);
            }

            channel.close();
            connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
